<template>
  <div class="error-distribution">
    <el-card v-loading="loading">
      <div class="header-controls">
        <el-radio-group v-model="questionType" @change="handleTypeChange">
          <el-radio-button :label="0">客观题</el-radio-button>
          <el-radio-button :label="1">主观题</el-radio-button>
        </el-radio-group>
        <!-- <el-radio-group v-model="chartType" @change="switchChartType">
          <el-radio-button label="bar">柱状图</el-radio-button>
          <el-radio-button label="line">折线图</el-radio-button>
        </el-radio-group> -->
      </div>
      <div class="content-wrapper">
        <div class="chart-container">
          <div ref="errorChart" style="width: 100%; height: 400px"></div>
        </div>
        <div class="table-container">
          <div class="table-header">
            <!-- <h4>第{{ selectedQuestion.questionNum }}题作答详情</h4> -->
            <div class="question-stats">
              <span>分值：{{ questionInfo.fullScore }}</span>
              <span>平均分：{{ questionInfo.avgScore }}</span>
              <span>最高分：{{ questionInfo.maxScore }}</span>
              <span>得分率：{{ questionInfo.scoreRate }}%</span>
            </div>
          </div>
          <el-table :data="detailData" border style="width: 100%" height="300" stripe
	      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
	      class="custom-table"
	      tooltip-effect="dark"
		  empty-text="">
            <el-table-column prop="scoreRange" label="得分情况" align="center" width="100" :sort-by="['scoreRange']" />
            <el-table-column label="作答人(试题分/总分)" align="left">
              <template slot-scope="scope">
                <el-popover
                  placement="top-start"
                  width="300"
                  trigger="hover">
                  <div class="students-list">
                    <p v-for="(student, index) in scope.row.students" :key="index">{{ student.name }}</p>
                  </div>
                  <div slot="reference" class="students-cell">
                    {{ scope.row.students.length }}人：
                    <span v-for="item in scope.row.students">{{ item.name }}</span>
                    <!-- {{ scope.row.students.slice(0, 3).join('、') }} -->
                    <span v-if="scope.row.students.length > 3">...</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="作答人数" align="center" width="100" />
			<!-- sortable -->
            <el-table-column prop="percentage" label="百分比" align="center" width="100" />
          </el-table>
          <div v-if="detailData.length<=0" class="empty-tip">
            <img src="../../../assets/image/empty.png" alt=""><br />点击左侧图表查看详情
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getErrorDistribution, getErrorDistributionDetail,getErrorquestionDetail } from '@/api/score'
import * as echarts from 'echarts'

export default {
  name: 'ErrorDistribution',
  props: {
    examId: {
      type: [String, Number],
      required: true
    },
    classId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      loading: false,
      questionType: 0, // 0-客观题 1-主观题
      chartType: 'bar',
      errorChart: null,
      chartData: [],
      selectedQuestion: null,
      detailData: [],
      questionInfo: {
        fullScore: 0,
        avgScore: '0.00',
        maxScore: 0,
        scoreRate: '0.00',
        examScoreRate: '0.00'
      },
      hasLoaded: false,
      intervalId: null,
      currentQuestionType: 'objective' // 默认客观题
    }
  },
  methods: {
    // async loadData() {
    //   if (!this.examId) return
      
    //   this.loading = true
    //   try {
    //     const { data } = await getErrorDistribution(this.examId, this.classId, this.questionType)
    //     this.chartData = data.questions
    //     this.updateChart()
    //   } catch (error) {
    //     console.error('加载错题分布数据失败:', error)
    //     this.$message.error('加载错题分布数据失败')
    //   } finally {
    //     this.loading = false
    //   }
    // },
	async loadData() {
		if (this.hasLoaded) return;
		this.chartData=[]
	  if (!this.examId) return
	  this.loading = true
	  try {
		  
	    const { data } = await getErrorquestionDetail(this.examId, this.classId, this.questionType)
      this.chartData = data.filter(item => item.isSubjectiveItem === this.questionType)
                         .sort((a, b) => a.questionNum - b.questionNum);
      console.log('Filtered chartData:', this.chartData);
      this.$nextTick(() => {
        this.updateChart();
        if (this.chartData.length > 0) {
          this.handleChartClick(this.chartData[0].questionId);
        }
      });
      this.hasLoaded = true;
      this.$nextTick(() => {
        this.updateChart(); // 数据加载完成后更新图表
      });
	  } catch (error) {
	    console.error('加载错题分布数据失败:', error)
	    this.$message.error('加载错题分布数据失败')
	  } finally {
	    this.loading = false
	  }
	},
    handleTypeChange(val) {
      this.hasLoaded = false
      this.questionType = val
      this.chartData=[]
      if (this.errorChart) {
        this.errorChart.dispose();
      }
        setTimeout(()=>{
          this.loadData()
          // this.updateChart()
        },200)
    },
    switchChartType() {
      this.updateChart()
    },
    
  updateChart() {
    if (!this.errorChart || this.chartData.length === 0) {
      console.warn('ECharts 未初始化或数据为空');
      return;
    }
    if (this.errorChart) {
      this.errorChart.dispose();
    }
    this.errorChart = echarts.init(this.$refs.errorChart);

    // 提取问题和堆叠数据
    const categories = this.chartData.map(item => `${item.questionNum}`);
    const seriesMap = {}; // 用于存储每个 scoreRange 的堆叠数据
    this.chartData.forEach(item => {
      item.details.forEach(detail => {
        const { scoreRange, percentage } = detail;
        const key = `${item.questionId}-${scoreRange}`;
        if (!seriesMap[key]) {
          seriesMap[key] = new Array(this.chartData.length).fill(null);
        }
        seriesMap[key][this.chartData.indexOf(item)] = {
          value: parseFloat(percentage),
          questionId: item.questionId,
        };
      });
    });
    
    // 获取所有的 `scoreRange` 并去重
    const scoreRanges = [...new Set(Object.keys(seriesMap).map(key => key.split('-')[1]))];
    // 将 `scoreRange` 与颜色数组对应起来
    const colorMap = {};
    const colors = ['#482FF7', '#6D59F9', '#9182FA', '#4451DD', '#5662E0', '#7881E6', '#81A7EC', '#46C3DB', '#6BCFE2'];
    
    scoreRanges.forEach((scoreRange, index) => {
      colorMap[scoreRange] = colors[index % colors.length];
    });
    
    // 将堆叠数据转换为 ECharts 需要的格式
    const series = Object.keys(seriesMap).map(key => {
      const scoreRange = key.split('-')[1]; // 提取 scoreRange
      return {
        name: scoreRange,
        type: 'bar',
        stack: 'total', // 堆叠到同一个柱子
        data: seriesMap[key].map(item => item ? item.value : null), // 确保没有 0%
        label: {
          show: true,
          position: 'inside',
          formatter: '{c}%', // 显示百分比
        },
        itemStyle: {
          color: colorMap[scoreRange] || '#909399', // 默认颜色
        },
      };
    });

    // 设置默认显示数量
    const defaultShowCount = 20;
    const showDataZoom = categories.length > defaultShowCount;

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow', // 鼠标滑过时显示阴影
        },
        formatter: function (params) {
          let tooltipText = `Question: ${categories[params[0].dataIndex]}<br>`;
          params.forEach(param => {
            if (param.value !== null && param.value !== undefined) {
              tooltipText += `${param.seriesName}: ${param.value}%<br>`;
            }
          });
          return tooltipText;
        },
      },
      xAxis: {
        type: 'category',
        data: categories, // 问题编号
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%', // Y 轴显示百分比
        },
      },
      series: series, // 堆叠数据
      dataZoom: showDataZoom ? [
        {
          type: 'slider',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: Math.round((defaultShowCount / categories.length) * 100),
          height: 20,
          bottom: 50,
          borderColor: 'transparent',
          backgroundColor: '#f5f5f5',
          fillerColor: '#295CFF',
          borderRadius: 80,
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '80%',
          handleStyle: {
            color: '#fff',
            shadowBlur: 3,
            shadowColor: '#295CFF',  // 调浅阴影颜色
            shadowOffsetX: 1,  // 减小阴影偏移
            shadowOffsetY: 1
          },
          textStyle: {
            color: '#666',  // 深紫色
            backgroundColor: 'rgba(230, 230, 250, 0.9)',  // 薰衣草浅紫
            borderRadius: 10,
            padding: [1, 3]
          },
          // 控制文本位置（关键）
          labelPosition: 'bottom', // 文本显示在滑块下方
        },
        {
          type: 'inside',
          xAxisIndex: [0],
          zoomOnMouseWheel: false,  // 禁用滚轮缩放
          moveOnMouseMove: true,     // 鼠标移动拖动
          moveOnMouseWheel: true,    // 滚轮平移
          zoomLock: true            // 锁定缩放比例
        }
      ] : [],
      grid: {
        bottom: showDataZoom ? 80 : 60,  // 动态调整间距（更紧凑）
        top: 40,                        // 统一顶部间距
        left: '3%',                     // 左侧留白
        right: '3%',                    // 右侧留白
        containLabel: true              // 确保标签不被截断
      }
    };
    this.errorChart.off('click');
    this.errorChart.on('click', (params) => {
      console.info('series',series)
      const seriesIndex = params.seriesIndex;
      const dataIndex = params.dataIndex;
      const questionId = seriesMap[Object.keys(seriesMap)[seriesIndex]][dataIndex]?.questionId;
      if (questionId) {
        this.handleChartClick(questionId)
      }
    });
    
    this.errorChart.setOption(option);
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', () => {
      this.errorChart && this.errorChart.resize();
    });
  },
    
    handleResize() {
      this.errorChart && this.errorChart.resize()
    },
    
    async handleChartClick(questionId) {
		console.info('questionId',questionId)
      this.loading = true
      // this.loadData()
      try {
        const { data } = await getErrorDistributionDetail(
          this.examId,
          this.classId,
          questionId
        )
        console.log('Detail data received:', data)
        this.detailData = data.details
        this.questionInfo = data.questionInfo
      } catch (error) {
        console.error('加载题目详情失败:', error)
        this.$message.error('加载题目详情失败')
      } finally {
        this.loading = false
      }
    },
  },
  mounted() {
    this.errorChart = echarts.init(this.$refs.errorChart)
    window.addEventListener('resize', this.handleResize)
    this.loadData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.errorChart) {
      this.errorChart.dispose()
      this.errorChart = null
    }
  },
  watch: {
    // 只在 examId 和 classId 都存在时才加载数据
    examId: {
      handler(newVal) {
        if (newVal && this.classId && !this.chartData.length) {
          this.loadData();
        }
      }
    },
    classId: {
      handler(newVal) {
        if (newVal && this.examId && !this.chartData.length) {
          this.loadData();
        }
      }
    },
    questionType: {
      handler() {
        if (this.examId && this.classId) {
          this.loadData();
        }
      }
    }
  }
}
</script>

<style scoped>

.header-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom:14px;
}
.content-wrapper {
  display: flex;
  gap: 14px;
}
.chart-container {
  width:calc(100% - 500px);
  border:solid 1px rgba(216,228,240,1);
  border-radius:10px;
}
.table-container {
  width: 500px;
  position: relative;
  height: 450px;
  display: flex;
  flex-direction: column;
}
.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
  background:#fff;
  padding:40px 0;
  color:#295CFF
}
.empty-tip img{
	padding:24px 0 16px;
}
.table-header {
  margin-bottom: 15px;
}
.question-stats {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}
.question-stats span {
  margin-right: 15px;
}
.question-stats span:last-child {
  margin-right: 0;
}
.students-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
.students-list {
  max-height: 300px;
  overflow-y: auto;
}
.students-list p {
  margin: 5px 0;
  line-height: 1.4;
}
.el-table {
  flex: 1;
}
.el-card.is-always-shadow, .el-card.is-hover-shadow:focus, .el-card.is-hover-shadow:hover, .el-cascader__dropdown, .el-color-picker__panel, .el-message-box, .el-notification{
	box-shadow: none;
}
.header-controls >>> .el-card__body, .header-controls >>> .el-main{
	padding:0 !important;
}
.header-controls >>> .el-card{
	border:none;
}
.header-controls >>> .el-radio-button__inner{
	border:solid 1px #295CFF;
	background:rgb(242, 246, 255);
	color:#295CFF;
	padding:7px 20px;
}
.header-controls >>> .el-radio-button__orig-radio:checked+.el-radio-button__inner{
	background:#295CFF;
	color:#fff;
}
.custom-table {
  width: 100%;
  border: 1px solid rgba(216,228,240,1);
  border-radius:10px;
  border-right: none;
  border-bottom:none;
  margin-top:0;
}
/* 自定义表格内部元素的样式 */
.custom-table >>> .el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height:42px;
  padding:0;
  text-align: center;
  font-weight:normal
}
.custom-table >>> .el-table__row td {
  height:42px;
  padding:0;
  text-align: center;
  border-bottom:none;
  border-right:solid 1px rgba(216,228,240,1);
}
.el-table .warning-row {
	background: #ffffff;
 }
.el-table .success-row {
	background: #D8E4F0;
}
</style> 